<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="礼物名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入礼物名称" />
      </el-form-item>
      <el-form-item label="礼物类型" prop="giftType">
        <el-select v-model="formData.giftType" placeholder="请选择礼物类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.GIFT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="限定标签" prop="tag">
        <el-input v-model="formData.tag" placeholder="请输入限定标签,例如:七夕限定" />
      </el-form-item>
      <el-form-item label="礼物图片" prop="img">
		<UploadImg v-model="formData.img" height="100px" width="100px" :limit="1" :is-show-tip="false" />
      </el-form-item>
      <el-form-item v-if="formData.giftType == 1" label="特效文件" prop="pic">
		<el-upload
		  ref="uploadRef"
		  v-model:file-list="fileList"
		  :action="uploadUrl"
		  :auto-upload="true"
		  :data="data"
		  :disabled="formLoading"
		  :limit="1"
		  :on-change="handleFileChange"
		  :on-error="submitFormError"
		  :on-exceed="handleExceed"
		  :on-success="submitFormSuccess"
		  :http-request="httpRequest"
		  accept=".svga"
		  drag
		>
		  <i class="el-icon-upload"></i>
		  <div class="el-upload__text"> 将文件拖到此处，或 <em>点击上传</em></div>
		  <template #tip>
		    <div class="el-upload__tip" style="color: red">
		      提示：仅允许导入 svga 格式文件！
		    </div>
		  </template>
		</el-upload>
      </el-form-item>
      <el-form-item label="金额" prop="money">
		<el-input-number v-model="formData.money" controls-position="right" :min="0" />
      </el-form-item>
      <el-form-item label="排序" prop="weigh">
		<el-input-number v-model="formData.weigh" controls-position="right" :min="0" />
      </el-form-item>
      <!-- <el-form-item label="限定开始时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="datetime"
          value-format="x"
          placeholder="选择限定开始时间"
        />
      </el-form-item>
      <el-form-item label="限定结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          value-format="x"
          placeholder="选择限定结束时间"
        />
      </el-form-item> -->
	  <el-form-item label="状态" prop="status">
	  		<el-switch
	  		  v-model="formData.status"
	  		  :active-value="true"
	  		  :inactive-value="false"
	  		/>
	  </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { fenToYuan, yuanToFen } from '@/utils'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { GiftApi, GiftVO } from '@/api/worker/gift'

/** 礼物 表单 */
defineOptions({ name: 'GiftForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  giftType: undefined,
  tag: undefined,
  img: undefined,
  pic: undefined,
  money: undefined,
  weigh: 0,
  startTime: undefined,
  endTime: undefined,
  status: true,
})
const formRules = reactive({
	name: [{ required: true, message: '礼物名称不能为空', trigger: 'blur' }],
	giftType: [{ required: true, message: '礼物类型不能为空', trigger: 'blur' }],
	img: [{ required: true, message: '礼物图片不能为空', trigger: 'blur' }],
	pic: [{ required: true, message: '特效文件不能为空', trigger: 'blur' }],
	money: [{ required: true, message: '礼物金额不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const fileList = ref([])
const data = ref({ path: '' })
const uploadRef = ref()
const { uploadUrl, httpRequest } = useUpload()

/** 处理上传的文件发生变化 */
const handleFileChange = (file) => {
  data.value.path = file.name
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

const submitFormSuccess = (e) => {
  formData.value.pic = e.data;
  // 清理
  formLoading.value = false
  // 提示成功，并刷新
  message.success('上传成功')
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await GiftApi.getGift(id)
	  formData.value.money = fenToYuan(formData.value.money)
    } finally {
      formLoading.value = false
    }
  }
  
  fileList.value = []
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    //const data = formData.value as unknown as GiftVO
	
	const data = { ...formData.value }
	data.money = yuanToFen(data.money)
	
    if (formType.value === 'create') {
      await GiftApi.createGift(data)
      message.success(t('common.createSuccess'))
    } else {
      await GiftApi.updateGift(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    giftType: undefined,
    tag: undefined,
    img: undefined,
    pic: undefined,
    money: undefined,
    weigh: 0,
    startTime: undefined,
    endTime: undefined,
    status: true,
  }
  formRef.value?.resetFields()
}
</script>